import { Card, message, Row, Col, Space } from 'antd';
import { history } from 'umi';
import ProCard from '@ant-design/pro-card';
import ProForm, {
  ProFormSelect,
  ProFormText,
  ProFormUploadButton,
  ProFormDependency,
  ProFormGroup,
  ProFormTextArea,
  ProFormList,
  ProFormDatePicker,
  ProFormRadio,
} from '@ant-design/pro-form';
import { useRequest } from 'umi';
import type { FC } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { fakeSubmitForm, queryDetail, update } from './service';
import {
  queryDictList,
  hospitalList,
  hospitalDeptlist,
  diseaseList,
} from '@/services/ant-design-pro/api';

const BasicForm: FC<Record<string, any>> = () => {
  const { run } = useRequest(fakeSubmitForm, {
    manual: true,
    onSuccess: () => {
      history.push('/doctor/doctor-list');
      message.success('提交成功');
    },
  });

  // const { data, loading } = useRequest(() => {
  //   if (history.location.query.id) {
  //     return queryDetail(history.location.query);
  //   }
  // });

  const onFinish = async (values: Record<string, any>) => {
    try {
      if (values.upload[0].response) {
        values.headPic = values.upload[0].response.data.url;
        delete values.upload;
      }
      var hospitalRelationList = [];
      console.log('values', values.attributes);
      for (var i = 0; i < values.attributes.length; i++) {
        let item = values.attributes[i];
        if (item.dept) {
          let obj = {};
          obj.deptFirstId = item.dept.value;
          obj.deptFirstName = item.dept.label;
          obj.deptSecondId = item.deptSecond.value;
          obj.deptSecondName = item.deptSecond.label;
          obj.hospitalId = item.hospital.value;
          obj.hospitalName = item.hospital.label;
          hospitalRelationList.push(obj);
        }
      }
      values.hospitalRelationList = hospitalRelationList;
      let labels = [];
      if (values.labels) {
        for (var i = 0; i < values.labels.length; i++) {
          let item = values.labels[i];
          let obj = item.year + '|' + item.honors;
          labels.push(obj);
        }
      }
      values.honors = labels.toString();
      console.log("organizationPosition------", values.organizationPosition);
      let organizationPosition = [];
      if (values.organizationPosition) {
        for (var i = 0; i < values.organizationPosition.length; i++) {
          let item = values.organizationPosition[i];
          let obj = item.organization + '|' + item.position;
          organizationPosition.push(obj);
        }
      }
      if (organizationPosition.toString() != "|")
        values.organizationPosition = organizationPosition.toString();
      // values.diseaseTags = values.diseaseTags.toString();
      // values.schemeTags = values.schemeTags.toString();
      let doctorTagsRelationList = [];
      for (var i = 0; i < values.diseaseTags.length; i++) {
        let item = values.diseaseTags[i];
        let obj = {};
        obj.tagId = item.value;
        obj.tagName = item.label;
        obj.tagType = 10;
        doctorTagsRelationList.push(obj);
      }
      for (var i = 0; i < values.schemeTags.length; i++) {
        let item = values.schemeTags[i];
        let obj = {};
        obj.tagId = item.value;
        obj.tagName = item.label;
        obj.tagType = 20;
        doctorTagsRelationList.push(obj);
      }
      values.doctorTagsRelationList = doctorTagsRelationList;
      if (values.gradeValue) {
        values.gradeId = values.gradeValue.value;
        values.grade = values.gradeValue.label;
      }
      if (values.edugradeValue) {
        values.edugradeId = values.edugradeValue.value;
        values.edugrade = values.edugradeValue.label;
      }
      delete values.attributes;
      delete values.labels;
    } catch (error) {
      console.log('error', error);
    }
    if (history.location.query.id) {
      values.id = history.location.query.id;
      try {
        const response = await update(values);
        if (response.code == 200) {
          message.success('修改成功');
        } else {
          message.error('修改失败!');
        }
      } catch (error) {
        console.log(error);
      }
    } else {
      run(values);
    }
  };

  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  };

  return (
    <PageContainer content="">
      <Card bordered={false}>
        <ProForm
          hideRequiredMark
          style={{ margin: '8', marginTop: 8 }}
          name="basic"
          layout="horizontal"
          // initialValues={data}
          onFinish={onFinish}
          {...formItemLayout}
          request={async () => {
            if (history.location.query.id) {
              return queryDetail(history.location.query).then(({ data }) => {
                console.log('data', data);
                try {
                  let diseaseTags = [];
                  let schemeTags = [];
                  for (var i = 0; i < data.doctorTagsRelationList.length; i++) {
                    let item = data.doctorTagsRelationList[i];
                    if (item.tagType == 10) {
                      let obj = { value: item.tagId, label: item.tagName, key: item.tagId };
                      diseaseTags.push(obj);
                    }
                    if (item.tagType == 20) {
                      let obj = { value: item.tagId, label: item.tagName, key: item.tagId };
                      schemeTags.push(obj);
                    }
                  }
                  data.diseaseTags = diseaseTags;
                  data.schemeTags = schemeTags;
                  let attributes = [];
                  for (var i = 0; i < data.doctorHospitalRelationList.length; i++) {
                    let item = data.doctorHospitalRelationList[i];
                    let dept = {};
                    dept.value = item.deptFirstId;
                    dept.label = item.deptFirstName;
                    data.dept = dept;
                    let deptSecond = {};
                    deptSecond.value = item.deptSecondId;
                    deptSecond.label = item.deptSecondName;
                    data.deptSecond = deptSecond;
                    let hospital = {};
                    hospital.value = item.hospitalId;
                    hospital.label = item.hospitalName;
                    data.hospital = hospital;
                    let obj = { dept: dept, deptSecond: deptSecond, hospital: hospital };
                    attributes.push(obj);
                  }
                  data.attributes = attributes;

                  let labels = [];
                  if (data.honors != '' && data.honors != null) {
                    let honors = data.honors.split(',');
                    for (var i = 0; i < honors.length; i++) {
                      let item = honors[i];
                      let honor = item.split('|');
                      if (honor.length > 0) {
                        let honorObj = {};
                        if (honor[0] != 'undefined') {
                          honorObj.year = honor[0];
                          honorObj.honors = honor[1];
                          labels.push(honorObj);
                        }
                      }
                    }
                  }
                  data.labels = labels;
                  if (data.organizationPosition != null && data.organizationPosition != "") {
                    let organizations = data.organizationPosition.split(',');
                    let organizationPosition = [];
                    for (var i = 0; i < organizations.length; i++) {
                      let item = organizations[i];
                      let organization = item.split('|');
                      if (organization.length > 0) {
                        let organizationObj = {};
                        organizationObj.organization = organization[0];
                        organizationObj.position = organization[1];
                        organizationPosition.push(organizationObj);
                      }
                    }
                    data.organizationPosition = organizationPosition;
                    console.log('organizationPosition', organizationPosition);
                  }

                  data.isExpert = data.isExpert + '';
                  let gradeValue = {};
                  gradeValue.value = data.gradeId;
                  gradeValue.label = data.grade;
                  data.gradeValue = gradeValue;
                  let edugradeValue = {};
                  edugradeValue.value = data.gradeId;
                  edugradeValue.label = data.grade;
                  data.edugradeValue = edugradeValue;
                  //data.edugradeId = data.edugradeId + '';
                  if (data.headPic) {
                    data.upload = [
                      {
                        uid: '1',
                        name: 'icon',
                        status: 'done',
                        url: 'http://oss.yizuoyiyou.com.cn' + data.headPic,
                      },
                    ];
                  }
                } catch (e) {
                  console.log(e);
                }
                return data;
              });
            } else {
              return {};
            }
          }}
          submitter={{
            render: (props, doms) => {
              return (
                <Row>
                  <Col span={14} offset={4}>
                    <Space>{doms}</Space>
                  </Col>
                </Row>
              );
            },
          }}
        >
          <Card bordered={false} title="医生基本信息">
            <ProFormText
              width="md"
              label="医生姓名"
              name="name"
              rules={[
                {
                  required: true,
                  message: '请输入医生姓名',
                },
              ]}
              placeholder="请输入医生姓名"
            />
            <ProFormUploadButton
              name="upload"
              label="医生头像"
              max={1}
              fieldProps={{
                name: 'file',
                listType: 'picture-card',
              }}
              action="/api/file/upload"
            //action="/api/file/oss"
            />
            <ProFormSelect
              width="md"
              name="gradeValue"
              fieldProps={{
                labelInValue: true,
              }}
              label="医生技术职称"
              request={async () => {
                const params = { dictCode: 'doctorGrade' };
                return queryDictList(params).then(({ data }) => {
                  return data.map((item) => {
                    return {
                      label: item.itemName,
                      value: item.itemValue,
                    };
                  });
                });
              }}
            />
            <ProFormSelect
              width="md"
              name="edugradeValue"
              fieldProps={{
                labelInValue: true,
              }}
              label="医生教学职称"
              request={async () => {
                const params = { dictCode: 'doctorEdugrade' };
                return queryDictList(params).then(({ data }) => {
                  return data.map((item) => {
                    return {
                      label: item.itemName,
                      value: item.itemValue,
                    };
                  });
                });
              }}
            />
          </Card>
          <Card bordered={false} title="执业地点信息">
            <ProFormList
              name="attributes"
              // label=" "
              creatorButtonProps={{
                creatorButtonText: '添加多点执业信息',
                // icon: false,
                type: 'link',
                style: { width: 'unset' },
              }}
              min={1}
              copyIconProps={false}
              itemRender={({ listDom, action }, { index }) => (
                <ProCard
                  style={{ marginLeft: 180 }}
                  // title={`规格${index + 1}`}
                  extra={action}
                  bodyStyle={{ paddingBlockEnd: 0 }}
                >
                  {listDom}
                </ProCard>
              )}
            //  creatorRecord={{ name: '', items: [{ name: '' }] }}
            // initialValue={[{}]}
            >
              <ProFormSelect
                width="md"
                name="hospital"
                label="第一执业地点"
                showSearch
                fieldProps={{
                  labelInValue: true,
                  labelCol: { span: 8 },
                  wrapperCol: { span: 14 },
                }}
                request={async ({ keyWords }) => {
                  let query = {
                    likeQuery: {
                      name: keyWords,
                    },
                    pageNum: 1,
                    pageSize: 20,
                  };
                  return hospitalList(query).then(({ data }) => {
                    return data.list.map((item) => {
                      return {
                        label: item.name,
                        value: item.id,
                      };
                    });
                  });
                }}
              />
              <ProFormDependency name={['hospital']}>
                {({ hospital }) => {
                  return (
                    <ProFormGroup
                      key={hospital ?.value}
                    // params={{
                    //   key: hospital?.value,
                    // }}
                    >
                      <ProFormSelect
                        width="150px"
                        params={{
                          key: hospital ?.value,
                        }}
                        name="dept"
                        label="科室"
                        showSearch
                        fieldProps={{
                          labelInValue: true,
                        }}
                        request={async () => {
                          console.log('hospital', hospital);
                          let query = {
                            eqQuery: {
                              hospitalId: hospital.key,
                              level: 1,
                            },
                            pageNum: 1,
                            pageSize: 20,
                          };

                          // let arr = user.split('-');
                          return hospitalDeptlist(query).then(({ data }) => {
                            return data.list.map((item) => {
                              return {
                                label: item.name,
                                value: item.id,
                              };
                            });
                          });
                        }}
                      />
                      <ProFormDependency name={['dept']}>
                        {({ dept }) => {
                          return (
                            <ProFormSelect
                              params={{
                                key: dept ?.value,
                              }}
                              width="150px"
                              name="deptSecond"
                              fieldProps={{
                                labelInValue: true,
                              }}
                              request={async () => {
                                // let arr = user.split('-');
                                let query = {
                                  eqQuery: {
                                    parentId: dept.key,
                                  },
                                  pageNum: 1,
                                  pageSize: 20,
                                };
                                return hospitalDeptlist(query).then(({ data }) => {
                                  return data.list.map((item) => {
                                    return {
                                      label: item.name,
                                      value: item.id,
                                    };
                                  });
                                });
                              }}
                            />
                          );
                        }}
                      </ProFormDependency>
                    </ProFormGroup>
                  );
                }}
              </ProFormDependency>
            </ProFormList>
          </Card>
          <Card bordered={false} title="详细信息">
            <ProFormTextArea name="specialize" label="擅长" placeholder="请输入擅长" />
            <ProFormTextArea
              name="intro"
              label="简介"
              placeholder="请输入简介"
              fieldProps={{
                rows: 8,
              }}
            />
            <ProFormTextArea
              name="clinicalExpertise"
              label="临床专长"
              placeholder="请输入临床专长"
            />
            <ProFormTextArea name="diseaseTxt" label="擅长疾病" placeholder="请输入擅长疾病" />
            <ProFormList
              name="organizationPosition"
              label="现任职务"
              //  initialValue={[{}]}
              creatorButtonProps={{
                creatorButtonText: '添加其他职位',
                // icon: false,
                type: 'link',
                style: { width: 'unset' },
              }}
              min={1}
              copyIconProps={false}
            >
              <ProFormGroup key="organizationGroup">
                <ProFormText
                  name="organization"
                  rules={[
                    {
                      required: false,
                      message: '请输入任职机构',
                    },
                  ]}
                  placeholder="请输入任职机构"
                />
                <ProFormText
                  width="md"
                  name="position"
                  rules={[
                    {
                      required: false,
                      message: '请输入职位',
                    },
                  ]}
                  placeholder="请输入职位"
                />
              </ProFormGroup>
            </ProFormList>
            <ProFormTextArea
              name="mainResearchDirections"
              label="主要研究方向"
              placeholder="请输入主要研究方向"
              width="md"
            />
            <ProFormList
              name="labels"
              label="荣誉"
              //initialValue={[{}]}
              creatorButtonProps={{
                creatorButtonText: '添加其他荣誉',
                // icon: false,
                type: 'link',
                style: { width: 'unset' },
              }}
              min={1}
              copyIconProps={false}
            >
              <ProFormGroup key="organizationGroup">
                <ProFormDatePicker.Year name="year" placeholder="请选择荣誉授予年份" />
                <ProFormText
                  name="honors"
                  rules={[
                    {
                      required: true,
                      message: '请输入荣誉',
                    },
                  ]}
                  placeholder="请输入荣誉"
                />
              </ProFormGroup>
            </ProFormList>
          </Card>
          <Card bordered={false} title="标签">
            <ProFormSelect
              width="md"
              name="diseaseTags"
              label="擅长疾病"
              fieldProps={{
                labelInValue: true,
                mode: 'multiple',
              }}
              showSearch
              request={async ({ keyWords }) => {
                let query = {
                  likeQuery: {
                    name: keyWords,
                  },
                  pageNum: 1,
                  pageSize: 20,
                };
                return diseaseList(query).then(({ data }) => {
                  return data.list.map((item) => {
                    return {
                      label: item.name,
                      value: item.id,
                    };
                  });
                });
              }}
            />
            <ProFormSelect
              width="md"
              name="schemeTags"
              label="擅长方案"
              fieldProps={{
                labelInValue: true,
                mode: 'multiple',
              }}
              // showSearch
              request={async () => {
                const params = { dictCode: 'goodScheme' };
                return queryDictList(params).then(({ data }) => {
                  return data.map((item) => {
                    return {
                      label: item.itemName,
                      value: item.id,
                    };
                  });
                });
              }}
            />
            <ProFormRadio.Group
              options={[
                {
                  value: '1',
                  label: '是',
                },
                {
                  value: '0',
                  label: '否',
                },
              ]}
              label="是否专家"
              name="isExpert"
            />
            <ProFormDependency name={['isExpert']}>
              {({ isExpert }) => {
                if (isExpert && isExpert === '1') {
                  return (
                    <ProFormText
                      name="expertDesc"
                      label="专家描述"
                      width="md"
                      placeholder="请输入对专家的一句话描述，如国医大师"
                    />
                  );
                }
              }}
            </ProFormDependency>
          </Card>
        </ProForm>
      </Card>
    </PageContainer>
  );
};

export default BasicForm;
